﻿using Custom.Framework;
using Custom.Infrastructure;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Custom.Service
{
    public class SqlFileExecuter
    {

        private SqlSugarClient Db;

        public SqlFileExecuter()
        {
            Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = DBConnectionConfig.ConnectionString,
                DbType = DbType.Sqlite,
                InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息
                IsAutoCloseConnection = true,
            });
        }

        public void Exec(string fileName)
        {
            string sqlTxts = File.ReadAllText(fileName, Encoding.UTF8);
            string name = Path.GetFileName(fileName);
            if (name == "SysTaxCode.sql")   // 更新税收分类编码
            {
                string[] sqlArray = sqlTxts.Split('\n');

                Db.Ado.UseTranAsync(() =>
                {
                    foreach (string sql in sqlArray)
                    {
                        try
                        {
                            //string sqlText = sql.Replace("\'", "\\'");
                            Db.Ado.ExecuteCommand(sql);
                        }
                        catch (Exception ex)
                        {
                            //执行脚本错误
                            Logger.Error($"执行脚本[{sql}]", ex.Message);
                        }
                    }
                });
            }
            else
            { 
                string[] sqlArray = sqlTxts.Split(';');
           
                Db.Ado.UseTranAsync(() =>
                {
                    foreach (string sql in sqlArray)
                    {
                        try
                        {
                            Db.Ado.ExecuteCommand(sql);
                        }
                        catch (Exception ex)
                        {
                            //执行脚本错误
                            Logger.Error($"执行脚本[{sql}]", ex.Message);
                        }
                    }
                });
            }
        }
    }
}
